//
//  ProGoodsViewController.m
//  wedding
//
//  Created by 常宽 on 15/1/27.
//  Copyright (c) 2015年 常宽. All rights reserved.
//

#import "ProGoodsViewController.h"
#import "GoodsModel.h"//传进来的model和精品推荐的cell
#import "GoodsDetailsModel.h" // 本类的model
#import "ProItemViewController.h" // webView页
#import "PGoodsDetailsCell.h"   // 详情cell
#import "RecommendedCell.h"     // 精品推荐cell
#import "SectionrHeaderView.h"  // 自定义section类
#import "AppDelegate.h" //获取管理器类
#import "Goods.h"       //管理器model类

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height


@interface ProGoodsViewController ()<UITableViewDataSource, UITableViewDelegate>
// 数据数组
@property (nonatomic, retain)NSMutableArray *dataArray;
// 精品推荐数据数组
@property (nonatomic, retain)NSMutableArray *recommendedDataArray;
// tableView
@property (nonatomic, retain) UITableView *tableView;
// 管理器类
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

@end

@implementation ProGoodsViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.model = [[GoodsModel alloc] init];
        self.dataArray = [[NSMutableArray alloc] init];
        self.recommendedDataArray = [[NSMutableArray alloc] init];
        
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        self.managedObjectContext = app.managedObjectContext;
        
    }
    return self;
}
// 网络请求
- (void)netWorking
{
    NSString *url = [NSString stringWithFormat:@"http://hunliji.com/products/%@.json?user_id=(null)", self.model.idNumder];
    [NetHandler networkWithURL:url completion:^(id result) {
        NSDictionary *dic = [result objectForKey:@"product"];
        GoodsDetailsModel *model = [[GoodsDetailsModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.dataArray addObject:model];
        [self.tableView reloadData];
//        NSLog(@"model=====%@", model.introduce);
    }];
    
    NSString *urlRecommended = @"http://hunliji.com/productRecommend.json?count=6";
    [NetHandler networkWithURL:urlRecommended completion:^(id result) {
        NSArray *array = [result objectForKey:@"products"];
        for (NSDictionary *dic in array) {
            GoodsModel *model = [[GoodsModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.recommendedDataArray addObject:model];
        }
        [self.tableView reloadData];
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"商品详情";
    // 二级页面隐藏tabBar
    self.tabBarController.tabBar.hidden = YES;
    // 重写返回上级页面方法
    UIImage *backImage = [[UIImage imageNamed:@"返回.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem= [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(popBack:)];
    /// 分享/收藏/去购买的视图
    [self netWorking];
    [self createTableView];
    [self createTabBar];
}

// 返回上级页面
- (void)popBack:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 收藏分享购买按钮
/// 创建个tabBar位置的视图
- (void)createTabBar
{
    UIView *tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT - 44 - 64, WIDTH, 44)];
    tabBarView.backgroundColor = [WebColor white];
    [self.view addSubview:tabBarView];
    [self.view bringSubviewToFront:tabBarView];
    
    CGFloat W = tabBarView.frame.size.width;
    CGFloat H = tabBarView.frame.size.height;
    // 分享按钮
    UIButton *share = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    share.frame = CGRectMake(10, 5, (W - 40) / 3, H - 10);
    share.layer.cornerRadius = 5;
    UIImage *shareImage = [[UIImage imageNamed:@"分享.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [share setImage:shareImage forState:UIControlStateNormal];
    [share setTitle:@"分享" forState:UIControlStateNormal];
    [share setTitleColor:[WebColor lightCoral] forState:UIControlStateNormal];
    [share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    [tabBarView addSubview:share];
    
    
    // 收藏按钮
    UIButton *collection = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    collection.frame = CGRectMake(20 + ((W - 40) / 3), 5, (W - 40) / 3, H - 10);
    collection.layer.cornerRadius = 5;
#warning 加判断本地是否已收藏
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Goods" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"idNumder"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    UIImage *collectionImage = [[UIImage imageNamed:@"未收藏.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [collection setImage:collectionImage forState:UIControlStateNormal];
    
    if (fetchedObjects != nil) {
        for (Goods *model in fetchedObjects) {
            if ([model.idNumder isEqualToString:[NSString stringWithFormat:@"%@", self.model.idNumder]]) {
                UIImage *collectionImage = [[UIImage imageNamed:@"已收藏.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                [collection setImage:collectionImage forState:UIControlStateNormal];
            }
        }
    }
    
    [collection setTitle:@"收藏" forState:UIControlStateNormal];
    [collection setTitleColor:[WebColor lightCoral] forState:UIControlStateNormal];
    [collection addTarget:self action:@selector(collectionAction:) forControlEvents:UIControlEventTouchUpInside];
    [tabBarView addSubview:collection];
    // 去购买
    UIButton *buy = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    buy.frame = CGRectMake(30 + ((W - 40) / 3 * 2), 5, (W - 40) / 3, H - 10);
    buy.layer.cornerRadius = 5;
    [buy setBackgroundColor:[WebColor lightCoral]];
    buy.titleLabel.font = [UIFont boldSystemFontOfSize:23.f];
    [buy setTitle:@"去购买" forState:UIControlStateNormal];
    [buy setTitleColor:[WebColor white] forState:UIControlStateNormal];
    [buy addTarget:self action:@selector(goToBuyAction:) forControlEvents:UIControlEventTouchUpInside];
    [tabBarView addSubview:buy];
    
}
/// 分享
- (void)shareAction:(UIButton *)shareButton
{
    
}
/// 收藏
- (void)collectionAction:(UIButton *)collectionButton
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Goods" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"idNumder"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects != nil) {
        for (Goods *model in fetchedObjects) {
            if ([model.idNumder isEqualToString:[NSString stringWithFormat:@"%@", self.model.idNumder]]) {
                // 已收藏,以下是删除收藏的代码
                [self.managedObjectContext deleteObject:model];
                NSError *errorDelete = nil;
                [self.managedObjectContext save:&errorDelete];
                if (errorDelete) {
                    NSLog(@"商品删除失败======%@", errorDelete);
                } else {
                    NSLog(@"删除成功");
                    UIImage *collectionImage = [[UIImage imageNamed:@"未收藏.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    [collectionButton setImage:collectionImage forState:UIControlStateNormal];
                }
                return;
            }
        }
    }
    // 未收藏,以下是收藏的实现
    NSEntityDescription *goodsED = [NSEntityDescription entityForName:@"Goods" inManagedObjectContext:self.managedObjectContext];
    
    Goods *goods = [[Goods alloc] initWithEntity:goodsED insertIntoManagedObjectContext:self.managedObjectContext];
    
    goods.photo_path = [NSString stringWithFormat:@"%@", self.model.photo_path];
    goods.idNumder = [NSString stringWithFormat:@"%@", self.model.idNumder];
    goods.width = [NSString stringWithFormat:@"%@", self.model.width];
    goods.height = [NSString stringWithFormat:@"%@", self.model.height];
    goods.like_count = [NSString stringWithFormat:@"%@", self.model.like_count];
    goods.like = [NSString stringWithFormat:@"%@", self.model.like];
    goods.price = [NSString stringWithFormat:@"%@", self.model.price];
    goods.subject_desc = @"";
    
    NSError *error1 = nil;
    [self.managedObjectContext save:&error1];
    if (error1) {
        NSLog(@"商品收藏失败======%@", error1);
    } else {
        NSLog(@"收藏成功");
        UIImage *collectionImage = [[UIImage imageNamed:@"已收藏.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [collectionButton setImage:collectionImage forState:UIControlStateNormal];
    }

    
}
/// 去购买
- (void)goToBuyAction:(UIButton *)buyButton
{
    ProItemViewController *itemView = [[ProItemViewController alloc] init];
    GoodsDetailsModel *model = [self.dataArray lastObject];
    itemView.urlString = model.buy_url;
    [self.navigationController pushViewController:itemView animated:YES];
}


#pragma mark -
/// 创建表视图
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 58) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
}

#pragma mark -
#pragma mark tabelView协议
///  section 个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
///  每个section里的row的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
///  返回tableView里的cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            static NSString *string = @"Commodity";
            PGoodsDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
            if (!cell) {
                cell = [[PGoodsDetailsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
            }
            cell.model = [self.dataArray lastObject];
            return cell;
        }
            break;
            
        default:
        {
            static NSString *string = @"ProductsRecommended";
            RecommendedCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
            if (!cell) {
                cell = [[RecommendedCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
            }
            cell.array = self.recommendedDataArray;
            cell.block = ^(GoodsModel *model){
                ProGoodsViewController *goodsController = [[ProGoodsViewController alloc] init];
                goodsController.model = model;
                [self.navigationController pushViewController:goodsController animated:YES];
            };
            return cell;

        }
            break;
    }
}
/// 返回row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            GoodsDetailsModel *model = [self.dataArray lastObject];
            if ([model.width floatValue] != 0.0f) {
                float w = [model.width floatValue];
                float h = [model.height floatValue];
                float H = (WIDTH / w) * h;
                return H + 25;
            } else {
                return HEIGHT * 0.5;
            }
        }
            break;
            
        default:
            return (WIDTH - 40) / 3 * 2 + 30;
            break;
    }
}
///  选中cell执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
        {
            ProItemViewController *itemView = [[ProItemViewController alloc] init];
            GoodsDetailsModel *model = [self.dataArray lastObject];
            itemView.urlString = model.buy_url;
            [self.navigationController pushViewController:itemView animated:YES];
        }
            break;
            
        default:
            break;
    }
}
///  section 高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // 分区的高度
    switch (section) {
        case 0:
            return 25;
            break;
        case 1:
            return 25;
            break;
        default:
            return 0;
            break;
    }
}

///  返回自定义sectionView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SectionrHeaderView *sectionView = [[SectionrHeaderView alloc]initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 25)];
    sectionView.layer.cornerRadius = 4.f;
    switch (section) {
        case 0:
        {
            GoodsDetailsModel *model = [self.dataArray lastObject];
            sectionView.title.font = [UIFont boldSystemFontOfSize:30.f];
            sectionView.title.text = model.introduce;
        }
            break;
        case 1:
        {
            sectionView.title.text = @"精品推荐";
        }
            break;
        default:
            break;
    }
    sectionView.tiaoZhuanBlock = ^(NSString *title){
        
    };
    return sectionView;
}


#pragma mark -












- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
